<?php
/**
 * 零售利润
 */
namespace app\manage\plugins\lingshou;
use think\Hook;
use think\Controller;

use app\common\cache\CacheData;

class Plugin extends Controller{

	public static $plugin_dir = 'lingshou';

	public static function init(){
		Hook::add('addMember',__CLASS__);
	}

	public static function getInstance(){
		$plugin = new Plugin;
		return $plugin;
	}

	/**
	 * 数据配送
	 * @return [type] [description]
	 */
	public function data_config(){
		$coins = \app\common\query\Coin::coinData();
		$coins = array_values($coins);
		$levels = \app\common\query\Level::levelData();
		return [
			'plugin_dir' => self::$plugin_dir,
			'coins' => $coins,
			'levels' => $levels,
		];
	}

	/**
	 * 保存货币配置
	 * @return [type] [description]
	 */
	public function saveCoinConfig(){
		$params = $this->request->only('data');
		$config_name = 'coin';
		
		$data = [];
		$config_total = 0;
		foreach($params['data'] as $value):
			if(isset($data[$value['coin_id']])){
				$this->error('货币类型不能重复');
			}
			$config_total += $value['config'];
			$data[$value['coin_id']] = $value;
		endforeach;

		if($config_total!=100){
			$this->error('货币配置百分比只和必须等于100%');
		}
		
		$insertData = [
			'plugin_dir' => self::$plugin_dir,
			'config_name' => $config_name,
			'config_value' => serialize($data),
		];

		$model = new \app\common\model\PluginConfig;
		if($model->where(['plugin_dir'=>$insertData['plugin_dir'],'config_name'=>$insertData['config_name']])->find()){
			// 如果存在该配置，则更新
			$model -> where([
				'plugin_dir'=>$insertData['plugin_dir'],
				'config_name'=>$insertData['config_name']
				]) -> update(['config_value'=>$insertData['config_value']]);
		}else{
			// 否则新增
			$model -> insert($insertData);
		}
		// 更新缓存
		$CACHE = CacheData::getInstance('PluginConfig');
		$CACHE->updateCache();
		$this->success('更新成功');
	}

	/**
	 * 保存推荐人配置
	 * @return [type] [description]
	 */
	public function saveInviterConfig(){
		$params = $this->request->only('data');
		$config_name = 'inviter';

		$postData = $params['data'];
		// 用level_id作为二层数组的键名
		$data = [];
		foreach($postData as $value):
			$data[] = array_combine(array_column($value, 'level_id'), $value);
		endforeach;

		$insertData = [
			'plugin_dir' => self::$plugin_dir,
			'config_name' => $config_name,
			'config_value' => serialize($data),
		];

		$model = new \app\common\model\PluginConfig;
		if($model->where(['plugin_dir'=>$insertData['plugin_dir'],'config_name'=>$insertData['config_name']])->find()){
			// 如果存在该配置，则更新
			$model -> where([
				'plugin_dir'=>$insertData['plugin_dir'],
				'config_name'=>$insertData['config_name']
				]) -> update(['config_value'=>$insertData['config_value']]);
		}else{
			// 否则新增
			$model -> insert($insertData);
		}
		// 更新缓存
		$CACHE = CacheData::getInstance('PluginConfig');
		$CACHE->updateCache();
		$this->success('更新成功');
	}


	/**
	 * 计算零售利润
	 * @param [type] &$params [description]
	 */
	public function addMember($data){
		$memberData = $data['member'];
		$score = $data['score'];
		$level_id = $memberData['level_id'];
		$mid = $memberData['mid'];

		// 获取本插件配置数据
		$pluginConfigQuery = new \app\common\query\PluginConfig;
		// 货币配置
		$coinConfig = $pluginConfigQuery::pluginConfig(self::$plugin_dir,'coin');
		$coinConfig = unserialize($coinConfig['config_value']);
		// 推荐人配置
		$inviterConfig = $pluginConfigQuery::pluginConfig(self::$plugin_dir,'inviter');
		$inviterConfig = unserialize($inviterConfig['config_value']);

		foreach($inviterConfig as $key => $config):
			// 该会员等级在第$key层级推荐人的配置
			$rate = $config[$level_id]['rate'];
			$max = $config[$level_id]['max'];
			// 该层级的推荐人mid
			$inviter_id = $this->getInviter($mid,$key);
			if(false==$inviter_id){
				// 如果该推荐层级没有推荐人，终止处理
				break;
			}
			// 对该推荐人按照该配置进行处理
			$this->inviterBonus($score,$inviter_id,$rate,$max,$coinConfig,$mid);
		endforeach;

		
	}

	private function inviterBonus($score,$inviter_id,$rate,$max,$coinConfig,$mid){
		$bonus = $score * $rate / 100;
		$memberCoinModel = new \app\common\model\MemberCoin;
		$pluginDataModel = new \app\common\model\PluginData;
		
		foreach($coinConfig as $config):
			$record = [
				'plugin_dir' => self::$plugin_dir,
				'reason_mid' => $mid,
				'effect_mid' => $inviter_id,
				'coin_id' => $config['coin_id'],
				'amount' => $bonus*$config['config']/100,
				'remark' => $mid.'注册产生零售利润',
				'create_time' => time(),
			];
			$recordAll[]=$record;
			
			// 推荐人奖金入账
			$memberCoinModel -> where(['mid'=>$inviter_id,'coin_id'=>$record['coin_id']]) -> setInc('amount',$record['amount']);
			
		endforeach;
		// 奖金记录
		$pluginDataModel->saveAll($recordAll);
	}

	/**
	 * 根据层级查找推荐人
	 * @param  [type] $index [description]
	 * @return [type]        [description]
	 */
	public function getInviter($mid,$index=0){
		// 循环查找次数
		$num = $index+1;
		$index_mid = $mid;
		$model = new \app\common\model\Member;

		for($i=$num;$i>0;$i--){
			$inviter = $model -> where('mid',$index_mid) -> find();
			if(!$inviter){
				return false;
			}
			$index_mid = $inviter['inviter_id'];
		}
		return $index_mid;
	}

	
	public function test($data){
		echo '#';
	}

}